#include "stdafx.h"
#include "BaseFunctions.h"
#include <sstream>
#include <algorithm>
#include <iomanip>
#include "StringFunction.h"

#ifdef _WIN32

namespace BaseFunction
{
	std::string CreateGUID()
	{
		GUID guid;
		::CoCreateGuid(&guid);
		std::stringstream stream;
		stream << std::hex << std::uppercase
			<< "{" << std::setw(8) << std::setfill('0') << guid.Data1
			<< "-" << std::setw(4) << std::setfill('0') << guid.Data2
			<< "-" << std::setw(4) << std::setfill('0') << guid.Data3
			<< "-";
		for(int i = 0; i < sizeof(guid.Data4); ++i)
		{
			if(i == 2)
				stream << "-";
			stream << std::hex << std::setw(2) << std::setfill('0') << (int)guid.Data4[i];
		}
		stream << "}";
		return stream.str();
	}

	std::string ConvertToString(double val)
	{
		std::stringstream stream;
		stream << val;
		return stream.str();
	}

	double ConvertToDouble(std::string val)
	{
		if (val.length() == 0)
			return 0;

		char p = val.at(0);
		if (p < '0' || p > '9')
			return 0;

		double result;
		std::stringstream stream;
		stream << val;
		stream >> result;
		return result;
	}

	void* FindFunctionFromModule(std::string path, std::string name, void** pFunc)
	{
		void* pModule = ::LoadLibrary(StringToWString(path).c_str());
		if(pModule == NULL)
			return NULL;

		void* pFuncAddress = (void*)::GetProcAddress((HMODULE)pModule, name.c_str());
		if(pFuncAddress)
		{
			*pFunc = pFuncAddress;
			return pModule;
		}
		DeleteModule(pModule);
		return NULL;
	}

	bool DeleteModule(void* pModule)
	{
		return ::FreeLibrary((HMODULE)pModule) != 0;
	}
}
#endif